<?php
namespace Asf\Database;


use DI\Container;
use function DI\factory;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\Query\Grammars\MySqlGrammar;
use Swoole\Coroutine;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;

class ConnectionResolver implements ConnectionResolverInterface
{
    /**
     * @var Container
     */
    public static $container;

    protected $databaseConfiguration;

    protected $pool;

    //初始化连接池
    public function __construct()
    {
        $this->databaseConfiguration = self::$container->get('mysql');
        self::$container->set(PDOPool::class, factory(function() {
            return new PDOPool((new PDOConfig)
                ->withHost($this->databaseConfiguration['host'])
                ->withPort($this->databaseConfiguration['port'])
                ->withDbName($this->databaseConfiguration['database'])
                ->withCharset($this->databaseConfiguration['charset'])
                ->withUsername($this->databaseConfiguration['username'])
                ->withPassword($this->databaseConfiguration['password']),
                $this->databaseConfiguration['worker_connection_length']
            );
        }));
    }

    /**
     * Get a database connection instance.
     *
     * @param string|null $name
     * @return \Illuminate\Database\ConnectionInterface
     */
    public function connection($name = null)
    {
        //从连接池获取连接,使用完之后放回连接池
        $pdo = self::$container->get(PDOPool::class)->get();
        $connection =  new Connection($pdo, $this->databaseConfiguration['database'], $this->databaseConfiguration['prefix']);
        $connection->setQueryGrammar(new MySqlGrammar());

        Coroutine::defer(function() use ($pdo) {
            self::$container->get(PDOPool::class)->put($pdo);
        });

        return $connection;
    }

    /**
     * Get the default connection name.
     *
     * @return string
     */
    public function getDefaultConnection()
    {
        return $this->connection();
    }

    public function getConnection($name = null)
    {
        return $this->connection($name);
    }

    /**
     * Set the default connection name.
     *
     * @param string $name
     * @return void
     */
    public function setDefaultConnection($name)
    {
        // TODO: Implement setDefaultConnection() method.
    }
}